package org.one.afternoon.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.one.afternoon.common.Result;
import org.one.afternoon.domain.Comment;
import org.one.afternoon.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value = "/comment")
public class CommentController {
    @Autowired
    private CommentService commentService;

    @CrossOrigin // 跨域访问
    @GetMapping("/all")
    public Result<List<Comment>> findAll(){
        List<Comment> commentList=commentService.list(null);
        return Result.success(commentList);
    }


    @CrossOrigin
    @PostMapping("/queryOne")
    @ResponseBody
    public Result<List<Comment>> queryOne(@RequestBody Comment comment) {
        LambdaQueryWrapper<Comment> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotBlank(comment.getAuthorName()),Comment::getAuthorName,comment.getAuthorName());
        List<Comment> commentList=commentService.list(lambdaQueryWrapper);
        return Result.success(commentList);
    }

    @CrossOrigin
    @PostMapping("/insertOne")
    @ResponseBody
    public Result<String> addOne(@RequestBody Comment comment) {
        boolean save = commentService.save(comment);
        if (!save){
            return Result.error("添加用户失败");
        }else {
            return Result.success("添加用户成功");
        }
    }

    @CrossOrigin
    @PostMapping("/deleteOne")
    @ResponseBody
    public Result<String> deleteOne(@RequestParam Integer index) {
        commentService.removeById(index);
        Result<String> result=Result.success("删除成功");
        return result;
    }

    @CrossOrigin
    @PostMapping("/updateOne")
    @ResponseBody
    public Result<String> updateOne(@RequestBody Comment comment) {
        LambdaUpdateWrapper<Comment> lambdaUpdateWrapper=new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(comment.getUsefulCount()!=null,Comment::getUsefulCount,comment.getUsefulCount())
                .set(StringUtils.isNotBlank(comment.getAuthorName()),Comment::getAuthorName,comment.getAuthorName())
                .set(StringUtils.isNotBlank(comment.getAuthorAvatar()),Comment::getAuthorAvatar,comment.getAuthorAvatar())
                .set(StringUtils.isNotBlank(comment.getContent()),Comment::getContent,comment.getContent());
        commentService.update(null,lambdaUpdateWrapper);
        return Result.success("修改成功");
    }
}
